﻿using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace SerialCommand
{
    struct ExecComm
    {
        public Func<string, Match, bool> action;
        public string regex;
    }
    internal class SerialCommRegex
    {
        Dictionary<string, ExecComm> target = new Dictionary<string, ExecComm>();
        static SerialCommRegex current;
        public static SerialCommRegex Current
        {
            get
            {
                if (current == null)
                    current = new SerialCommRegex();
                return current;
            }
        }
        private SerialCommRegex()
        {
        }
        private string LastLineString;
        public void execComm(string str)
        {
            string[] list = str.Split("\r\n");
            list[0] = LastLineString + list[0];
            LastLineString = list.Last();
            list[list.Length - 1] = "";
            foreach (string line in list)
            {
                var keys = new List<string>(target.Keys);
                for(int i = 0; i < keys.Count; i++) 
                {
                    var item = keys[i];
                    Regex regex = new Regex(target[item].regex);
                    Match match = regex.Match(line);
                    if (match.Success)
                    {
                        if (target[item].action(item, match))
                        {
                            unregister(item);
                        }
                    }
                }
            }
        }
        public void register(string targe, ExecComm action)
        {
            if (!target.ContainsKey(targe))
                target.Add(targe, action);
        }
        public void unregister(string targe)
        {
            target.Remove(targe);
        }
    }
}
